/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package otros;

import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.font.TextAttribute;
import java.awt.print.*;
import java.awt.print.PrinterJob;
import java.awt.print.PageFormat;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.AttributedString;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.AttributeSet;
import javax.print.attribute.HashAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.PrinterName;
import javax.swing.JTable;
import tablasSql.ConsultaBD;

/**
 *
 * @author FERRETERIA
 */


class ObjetoDeImpresion extends Component implements Printable{
    
    private boolean ticket;
    private DatosToImprimir d;
    int posY;
    String fuente;
    
    public ObjetoDeImpresion (boolean valor, DatosToImprimir d) {
        super();
        ticket = valor;
        this.d = d;
        if (ticket)
           fuente = Configuracion.getInstance().getProperty(Configuracion.FUENTE);
    } 
    
    public Image getImagen (String url) {
        URL imagenURL = null;
        try {
            imagenURL = new URL(url);
        } catch (MalformedURLException e) {
           e.printStackTrace();
        }
        return Toolkit.getDefaultToolkit().getImage(imagenURL);
    }
    final int CARACTER = 72;
    
    private int getIniPosX() { 
        if(!ticket)
            return 56;
        return 13;
    }
        
    public void EncabezadoA4(Graphics g){
         Graphics2D g2d = (Graphics2D) g;
         MediaTracker mt = new MediaTracker(this);
         //imagen
         String ruta;
         if (!ticket) {
            ruta = "file:/" + Util.getRuta().replace("\\", "/") + Configuracion.getInstance().getProperty(Configuracion.LOGO_IMP);
            if (ruta.contains("build"))
                ruta = "file:/D:/LogoFINAL.jpg";
         } else {
            ruta = "file:/" + Util.getRuta().replace("\\", "/") + Configuracion.getInstance().getProperty(Configuracion.LOGO_IMPT);
            if (ruta.contains("build"))
                ruta = "file:/D:/LogoFINALBN.jpg";
         }
    
         Image imagen = getImagen(ruta);
         mt.addImage(imagen,0);
         try {
             mt.waitForID(0);
         } catch (InterruptedException e) {
         }
         
         // datos
         if(!ticket) {
            int y = 10;
            posY = 116;
            int posX = getIniPosX();
            
            g.drawImage(imagen, 56, 56, 155, 46,this);

            g.setFont(new Font ("Calibri", Font.BOLD, 16));
            g.drawString("FEMERCA S.L.", posX, posY);      // x,y
            g.drawString(d.getCopia(), 400, posY);      
            g.setFont(new Font ("Calibri", Font.PLAIN, 10));
            g.drawString("C/San Sebastian nº60", posX, posY + y);
            g.drawString("Nº pag.: " + (d.getPagina()+1)+ "/"+d.getTotalPaginas(), 400, posY + y);
            g.drawString("38005     S/C de Tenerife", posX, posY + y * 2);

            AttributedString attributedString = new AttributedString ("Teléfono: 922 21 24 36");
            attributedString.addAttribute(TextAttribute.FONT,new Font ("Calibri", Font.PLAIN, 10));
            g.drawString (attributedString.getIterator (), posX, posY + y * 3);

            g.drawString("C.I.F:   B-38335535", posX, posY + y * 4);
            g.drawString("Email: ferreteriamercado@hotmail.com", posX, posY + y * 5);

            g.drawLine(posX, posY + 5 + y * 5, 540, posY + 5 + y * 5);
        }
        else {
            int x = getIniPosX();
            int y = 13;
            posY = 75;
            g.drawImage(imagen, 10, 8, 205, 58,this);
//            g.setFont(new Font ("Calibri", Font.BOLD, 14));
//            g.drawString("FERRETERIA MERCADO", 40, 12);      // x,y
//             
            g.setFont(new Font (fuente, Font.BOLD, 9));
            g.drawString("FEMERCA S.L.", x, posY);      // x,y
            g.drawString(d.getCopia(),150, posY+(2*y));
            
            g.setFont(new Font (fuente, Font.PLAIN, 9));
            g.drawString("C/San Sebastian nº60", x, posY+=y);
            g.drawString("38005     S/C de Tenerife", x, posY+=y);
            g.drawString("Teléfono: 922 21 24 36", x, posY+=y);
            g.drawString("C.I.F:   B-38335535", x, posY+=y);
            g.drawString("Email: ferreteriamercado@hotmail.com", x,posY+=y);

            g.drawLine(x, posY+=5, 210, posY);
        }    
    }
    
    private void DatosCliente(Graphics g) {
        int posX = getIniPosX();
        String tipo = "";
        switch (d.getTipoTicket()) {
            case 0:
                tipo = "FACTURA";
                break;
            case 1:
                tipo = "ALBARAN";
                break;
            case 2:
                tipo = "PRESUPUESTO";
                break;
            case 3:
                tipo = "FIADO";
                break;
        }
        int y, x;
        
        if(!ticket) {
            posY = 185;
            y = 14;
            x = posX;
                
            g.setFont(new Font ("Calibri", Font.BOLD, 14));
            g.drawString(tipo + " Nº: " + d.getNumTicket(), 339, posY);     
            g.setFont(new Font ("Calibri", Font.PLAIN, 14));
            g.drawString("Fecha: " + d.getFecha(), 339, posY+26);     
            
            g.setFont(new Font ("Calibri", Font.BOLD, 10));
            g.drawString("Cliente", x, posY);
            g.drawString("[ " + d.getCliNum() + " ]", x+54, posY);
            g.drawString("Nombre:", x, posY+y);
            g.drawString("Domicilio:", x, posY+y*3);
            g.drawString("Localidad:", x, posY+y*4);
            g.drawString("CIF/NIF:", x, posY+y*5);
            g.drawString("Cod.Postal:", x+140, posY+y*4);
            g.drawString("Teléfono:", x+140, posY+y*5);
            
            g.setFont(new Font ("Calibri", Font.PLAIN, 10));
            g.drawString(d.getCliNombre(), x+54, posY + y);
            g.drawString(d.getCliNomFiscal(), x+54, posY + y*2);
            g.drawString(d.getCliDomicilio(), x+54, posY + y*3);
            g.drawString(d.getCliLocalidad(), x+54, posY + y*4);
            g.drawString(d.getCliCIF(), x+54, posY + y*5);
            g.drawString(d.getCliCodPostal(), x+195+5, posY + y*4);
            g.drawString(d.getCliTelefono(), x+195, posY + y*5);
            
            g.drawLine(posX, posY + 5+y*5, 540, posY + 5+y*5);
            
        } else {
            posY += 13;
            y = 13;
            g.setFont(new Font (fuente, Font.BOLD, 9));
            g.drawString(tipo + " Nº: " + d.getNumTicket(), posX, posY);     
            g.setFont(new Font (fuente, Font.PLAIN, 9));
            g.drawString("Cliente [ " + d.getCliNum() + " ]", posX, posY+=y);            
            g.drawString("Fecha: " + d.getFecha(), 135, posY);       
            g.drawString("Nombre: " + d.getCliNombre(), posX, posY+=y);
            g.drawString("CIF/NIF: " + d.getCliCIF(), posX, posY+=y);   
        }
        
    }
    
    private String getFormatPrecio(Object valor, int d) {
        DecimalFormat df = null;
        switch(d) {
            case 2:
                df = new DecimalFormat("#0.00"); 
                break;
            case 3:
                df = new DecimalFormat("#0.000"); 
                break;
        }
        return String.valueOf(df.format(valor)).replace(".", ",") + "€";
    }
    
    private String hallarValor(Object margen, Object precio) {
        float m = Float.parseFloat(margen.toString().replace("%","").replace(",",".").trim());
        float p = Float.parseFloat(precio.toString().replace("€", "").replace(",",".").trim());
        return getFormatPrecio((1.0f+(m/100.0f))*p, 2);
    }
    
    public void Datos(Graphics g) {
        int posX = getIniPosX();
        int y, yLin;
        
        if(!ticket) {
            yLin = 272;
            g.drawLine(posX, 278, 540, 278);
            g.setFont(new Font ("Calibri", Font.BOLD, 12));
            g.drawString("Codigo", posX, yLin);
            g.drawString("Detalle", 175, yLin);
            g.drawString("Cant.", 350, yLin);
            g.drawString("Precio", 400, yLin);
            g.drawString("DTO.", 450, yLin);
            g.drawString("Importe", 500, yLin);
            
            y = 14;
            yLin = 290;
            g.setFont(new Font ("Calibri", Font.PLAIN, 10));
            JTable tabla = d.getTabla();
            int j = 0;
            for (int i = (d.getPagina()* 29); (i < tabla.getRowCount()-1) && (i < (d.getPagina()+1) *29); i++) {
                String cod = tabla.getValueAt(i, 1)!= null? String.valueOf(tabla.getValueAt(i, 1)) : "";
                g.drawString(cod, posX, yLin + y * j);
                g.drawString(String.valueOf(tabla.getValueAt(i, 2)), 100, yLin + y * j);    //detalle
                if (!tabla.getValueAt(i, 3).toString().equals("0.0")) {
                    g.drawString(String.valueOf(tabla.getValueAt(i, 3)), 350, yLin + y * j);    // cantidad   
                    g.drawString(hallarValor(tabla.getValueAt(i, 5), tabla.getValueAt(i, 4)), 400, yLin + y * j);   // precio + margen
                    g.drawString(String.valueOf(tabla.getValueAt(i, 6)), 450, yLin + y * j);    // descuento
                    g.drawString(getFormatPrecio(tabla.getValueAt(i, 7),2), 500, yLin + y * j);   // total
                }
                j++;
            }
            g.drawLine(posX, 690, 540, 690);
        }
        else {
            posY += 12;
            y = 13;
            g.setFont(new Font (fuente, Font.PLAIN, 9));
            g.drawString("PRODUCTO", posX, posY);
            g.drawString("CANT.", 75, posY);
            g.drawString("PVP", 106, posY);
            g.drawString("DTO.", 136, posY);
            g.drawString("IMPORTE", 167, posY);
            g.drawLine(posX, posY+=2, 210, posY);
            
            
            JTable tabla = d.getTabla();
            for (int i = 0; i < tabla.getRowCount()-1; i++) {
                g.setFont(new Font (fuente, Font.PLAIN, 8));
                String cod = tabla.getValueAt(i, 1)!= null? String.valueOf(tabla.getValueAt(i, 1))+"-" : "";
                g.drawString(cod+String.valueOf(tabla.getValueAt(i, 2)), posX, posY += y);
                g.setFont(new Font (fuente, Font.PLAIN, 9));
                if (!tabla.getValueAt(i, 3).toString().equals("0.0")) {
                    g.drawString(String.valueOf(tabla.getValueAt(i, 3)), 75, posY += y);
                    g.drawString(hallarValor(tabla.getValueAt(i, 5), tabla.getValueAt(i, 4)), 103, posY);
                    g.drawString(String.valueOf(tabla.getValueAt(i, 6)), 136, posY);
                    g.drawString(getFormatPrecio(tabla.getValueAt(i, 7),2), 167, posY);
                }
            }
        }
    }
    
    public void Pie(Graphics g) {
        int posX = getIniPosX();
        int y;
        
        float descuento = Float.valueOf(d.getDescPie().replace("%", "").replace(",",".").trim());
        float pFinalMano = Float.valueOf(d.getPrecioMano());
        float pBruto = Float.valueOf(d.getPrecioBruto().replace("€", "").replace(",",".").trim());
        float pFinal;
        float descuento2 = 0;

        if (pFinalMano > 0) {
            pFinal = pFinalMano;
            if(pFinalMano < pBruto)
               descuento2 = pFinalMano-pBruto;
        } else 
            if (pFinalMano == -1) {
                pFinal = 0;
                descuento2 = pBruto ;
            }
            else 
                pFinal = pBruto - (pBruto * descuento / 100);  
        
        
        if (!ticket) {
            y = 14;
            posY = 690;    
            if (d.getPagina()+1 == d.getTotalPaginas()) {
                g.setFont(new Font ("Calibri", Font.PLAIN, 10));
                g.drawString("Recibí conforme (Firma/Sello)", 115, posY+y);
                g.drawString("COMERCIANTE MINORISTA", 235, posY+5+y*7);

                g.drawString("Total Bruto..............", 400, posY+y);
                g.drawString("Descuento...............", 400, posY+y*2);
                g.drawString("Total IGIC................. 0,00", 400, posY+y*3);

                g.drawString("Comentario: " + d.getComentario(), posX, posY+y*6);

                int xCol = 485;
                g.drawString(d.getPrecioBruto(), xCol, posY+y); 
                if (pFinalMano > 0)
                    g.drawString(getFormatPrecio(descuento2, 2), xCol, posY+y*2);
                else
                    g.drawString(d.getDescPie(), xCol, posY+y*2);

                g.setFont(new Font ("Calibri", Font.BOLD, 16));
                g.drawString("TOTAL..........", 400, posY+y*4+2);
                g.drawString(getFormatPrecio(pFinal, 2), xCol, posY+y*4+2);
                if (d.getEntregado() != null) {
                    float entregado = Float.parseFloat(d.getEntregado());
                    g.setFont(new Font ("Calibri", Font.PLAIN, 10));
                    g.drawString("Entregado.................", 400, posY+y*5);
                    g.drawString(getFormatPrecio(entregado, 2), xCol, posY+y*5);
                    g.drawString("Cambio.....................", 400, posY+y*6);
                    g.drawString(getFormatPrecio(entregado-pFinal, 2), xCol, posY+y*6);
                }
            } else {
                g.setFont(new Font ("Calibri", Font.BOLD, 16));
                g.drawString("Pagina: " + (d.getPagina()+1) + "/" + d.getTotalPaginas(), 245, posY+5+y*4);
            }
            
        } else {
            y = 13;
            
            g.drawString("Total Bruto ", 116, posY+=y*2);
            g.drawString(d.getPrecioBruto(), 167, posY);
            g.drawString("Firma del cliente", 27, posY);
            g.drawString("Descuento", 116, posY+=y);
            if (descuento2 != 0)
                g.drawString(getFormatPrecio(descuento2, 2), 167, posY);
            else
                g.drawString(d.getDescPie(), 167, posY);
         
            g.drawString("Total IGIC", 116, posY+=y);
            g.drawString("0.00€", 167, posY);
            g.setFont(new Font (fuente, Font.BOLD, 11));
            g.drawString("TOTAL", 116, posY+=y+5);
            g.drawString(getFormatPrecio(pFinal, 2), 167, posY);
            if (d.getEntregado() != null) {
                float entregado = Float.parseFloat(d.getEntregado());
                g.setFont(new Font (fuente, Font.PLAIN, 9));
                g.drawString("Entregado", 116, posY+=y);
                g.drawString(getFormatPrecio(entregado, 2), 167, posY);
                g.drawString("Cambio", 116, posY+=y);
                g.drawString(getFormatPrecio(entregado-pFinal, 2), 167, posY);
            }
            g.setFont(new Font (fuente, Font.PLAIN, 8));
            g.drawString("COMERCIANTE MINORISTA", 60, posY+=y*2);
            g.drawString("NO SE ACEPTAN DEVOLUCIONES SIN EL TICKET", posX, posY+=y);
        }
    }
               
    public int print(Graphics g, PageFormat f, int pageIndex){
        d.setCopia((pageIndex / d.getTotalPaginas() == 0) && (!d.isNoOriginal()) ? "ORIGINAL" : "COPIA");
        if (d.getTotalPaginas()*(1+d.getNumCopias()) > pageIndex) {
           d.setPagina(pageIndex % d.getTotalPaginas());
           EncabezadoA4(g);
           DatosCliente(g);
           Datos(g); 
           Pie(g);
           return PAGE_EXISTS;
        }
        else
            return NO_SUCH_PAGE;
    }
}

public class ImpVenta {
    
    static boolean ticket = true;
    static String impresora;
    private final static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(ImpVenta.class);
    
//    void ImpVenta (boolean ticket) {
//        this.ticket = ticket;
//        setImpresora();
//    }
    
    static void setImpresora (int imp) {
        ticket = false;
        switch(imp) {
        case 0:
            impresora = Configuracion.getInstance().getProperty(Configuracion.IMP_NORMAL);
            break;
        case 1:
            ticket = true;
            impresora = Configuracion.getInstance().getProperty(Configuracion.IMP_TICKET);
            break;
        case 2:
            impresora = Configuracion.getInstance().getProperty(Configuracion.IMP_PDF);
            break;
        }   
    }
    
    static private String getNombreImpreso(DatosToImprimir d) {
        String nombre= "";
        switch(d.getTipoTicket()) {
            case 0: nombre = "Factura"; 
                break;
            case 1: nombre = "Albaran";
                break;
            case 2: nombre = "Presupuesto";
                break; 
            case 3: nombre = "Fiado";
                break;
        }
        return nombre+d.getNumTicket();
    }
    
    static public void imprime(int imp, DatosToImprimir d){
        ConsultaBD.cursorEspera(null);
        setImpresora(imp);
        PrinterJob job = PrinterJob.getPrinterJob();
        PageFormat pf = job.defaultPage();
        Paper paper = new Paper();
        double margin;
        if (ticket) {
            //paper.setSize(30*72, 5000);
            paper.setSize(226.67, paper.getHeight() + 28.33*d.getTabla().getRowCount()*2);  
            margin = 0.5;
        }
        else {
            paper.setSize(595.0,842.0); // (8.26*72, 11.69*72)   21x29.7cm     ancho y alto  A4
            margin = 10;
        }
        
        paper.setImageableArea(margin, margin, paper.getWidth()-margin, paper.getHeight()-margin);
        pf.setPaper(paper);
        pf.setOrientation(PageFormat.PORTRAIT);  // vertical
        String nameImp = getNombreImpreso(d);
        
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
        for (PrintService printService : services) {
            if (printService.getName().equals(impresora)) {
                try {
                    job.setPrintService(printService);
                    break;
                } catch (PrinterException ex) {
                    System.out.println(ex);
                }
            }
        }
        //if(job.printDialog()){
            try{
               if (!ticket) {
                   int tamLista = d.getTabla().getRowCount();
                   if (d.getTabla().getValueAt(tamLista-1, 1) == null)
                       tamLista--;
                   int hojas = tamLista/29;
                   if (tamLista%29 == 0)
                        hojas--;
                   d.setTotalPaginas(hojas);      
                   job.setJobName(nameImp);
                   job.setPrintable(new ObjetoDeImpresion(ticket, d), pf);  
                   job.print();
               }
               else {
                    job.setPrintable(new ObjetoDeImpresion(ticket, d), pf);  
                    job.print();
               }
            }catch(PrinterException e){
                System.out.println(e);
            }
        //}
            ConsultaBD.cursorNormal(null);
    }
    
    static public void abrirCajon() {
        try {
            String apertura = Configuracion.getInstance().getProperty(Configuracion.CAJON_COD);
            String impCajon = Configuracion.getInstance().getProperty(Configuracion.CAJON);
            
            //busco la impresora
            AttributeSet attributeSet = new HashAttributeSet();
            attributeSet.add(new PrinterName(impCajon, null));
            PrintService[] services = PrintServiceLookup.lookupPrintServices(null, attributeSet);
            DocPrintJob printJob = services[0].createPrintJob();
            // preparo la informacion q le envio a la impresora
            DocFlavor docFormat = DocFlavor.BYTE_ARRAY.AUTOSENSE;
            String [] cod = apertura.split(",");
            byte[] bytes = new byte[cod.length];
            for (int i = 0; i < cod.length; i++)
                bytes [i] = Byte.valueOf(cod[i]);
            Doc document = new SimpleDoc(bytes, docFormat, null);
            //Envio a la impresora
            printJob.print(document, new HashPrintRequestAttributeSet());
        } catch (PrintException ex) {
            log.error("abrirCajon: impresora de ticket " + ex);
        }
    }
}
